package com.qianheng.kit.base.java.reactor.v1;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.util.Iterator;
import java.util.Set;

import com.qianheng.kit.base.java.reactor.NioDemoConfig;
import com.qianheng.kit.base.java.reactor.v1.handler.AcceptorHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * 反应器
 * 实现简单回显服务
 */
@Slf4j
public class EchoServerReactor implements Runnable {
    Selector acceptSelector;
    ServerSocketChannel serverSocketChannel;

    EchoServerReactor() throws IOException {
        // 1.获取选择器
        acceptSelector = Selector.open();
        // 2.获取通道
        serverSocketChannel = ServerSocketChannel.open();
        // 3.设置为非阻塞
        serverSocketChannel.configureBlocking(false);
        // 4.绑定端口
        serverSocketChannel.bind(new InetSocketAddress(NioDemoConfig.SOCKET_SERVER_PORT));
        log.info("服务器启动成功");
        // 5.将通道注册的“接收新连接”IO 事件，注册到选择器上
        SelectionKey sk = serverSocketChannel.register(acceptSelector, SelectionKey.OP_ACCEPT);
        //将新连接处理器作为附件，绑定到 sk 选择键
        sk.attach(new AcceptorHandler(acceptSelector, serverSocketChannel));
    }

    //轮询和分发事件
    public void run() {
        try {
            while (!Thread.interrupted()) {
                acceptSelector.select();
                Set<SelectionKey> selected = acceptSelector.selectedKeys();
                Iterator<SelectionKey> it = selected.iterator();
                while (it.hasNext()) {
                    //反应器负责dispatch收到的事件
                    SelectionKey sk = it.next();
                    dispatch(sk);
                }
                selected.clear();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    void dispatch(SelectionKey sk) {
        Runnable handler = (Runnable)sk.attachment();
        //调用之前attach绑定到选择键的handler处理器对象
        if (handler != null) {
            handler.run();
        }
    }

    public static void main(String[] args) throws IOException {
        new Thread(new EchoServerReactor()).start();
    }
}